<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="代金券标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入代金券标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择优惠券类型">
          <el-option label="全部" value="" />
          <el-option label="普通券" value="0" />
          <el-option label="秒杀券" value="1" />
        </el-select>
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态">
          <el-option label="全部" value="" />
          <el-option label="上架" value="1" />
          <el-option label="下架" value="2" />
          <el-option label="过期" value="3" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:voucher:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:voucher:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:voucher:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:voucher:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="voucherList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="代金券标题" align="center" prop="title" />
      <el-table-column label="副标题" align="center" prop="subTitle" />
      <el-table-column label="使用规则" align="center" prop="rules" />
      <el-table-column label="支付金额(分)" align="center" prop="payValue" />
      <el-table-column label="抵扣金额(分)" align="center" prop="actualValue" />
      <el-table-column label="类型" align="center" prop="type">
        <template slot-scope="scope">
          <el-tag :type="getTypeTag(scope.row.type)">
            {{ typeMap[scope.row.type] }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ statusMap[scope.row.status] }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:voucher:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:voucher:remove']"
          >删除</el-button>

          <el-button
            v-if="canToggleStatus(scope.row.status)"
            size="mini"
            type="text"
            :icon="getToggleIcon(scope.row.status)"
            :style="{ color: getToggleColor(scope.row.status) }"
            @click="toggleStatus(scope.row)"
            v-hasPermi="['system:voucher:status']"
          >
            {{ getToggleText(scope.row.status) }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">

        <el-form-item label="商店" prop="shopId">
          <el-select v-model="form.shopId" placeholder="请选择商店">
            <el-option
              v-for="shop in shopList"
              :key="shop.id"
              :label="shop.name"
              :value="shop.id">
              {{ shop.name }}
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="代金券标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入代金券标题" />
        </el-form-item>

        <el-form-item label="副标题" prop="subTitle">
          <el-input v-model="form.subTitle" placeholder="请输入副标题" />
        </el-form-item>

        <el-form-item label="使用规则" prop="rules">
          <el-input v-model="form.rules" type="textarea" placeholder="请输入内容" />
        </el-form-item>

        <el-form-item label="支付金额(分)" prop="payValue">
          <el-input
            v-model.number="form.payValue"
            placeholder="请输入支付金额(分)"
            @input="handleNumberInput('payValue')"
          />
        </el-form-item>

        <el-form-item label="抵扣金额(分)" prop="actualValue">
          <el-input
            v-model.number="form.actualValue"
            placeholder="请输入抵扣金额(分)"
            @input="handleNumberInput('actualValue')"
          />
        </el-form-item>

        <el-form-item label="类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择优惠券类型">
            <el-option label="普通券" value="0" />
            <el-option label="秒杀券" value="1" />
          </el-select>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">上架</el-radio>
            <el-radio :label="2">下架</el-radio>
            <el-radio :label="3">过期</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listVoucher, getAllShopName,getVoucher, delVoucher, addVoucher, updateVoucher, changeVoucherStatus } from "@/api/system/voucher";

export default {
  name: "Voucher",
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      voucherList: [],
      title: "",
      open: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        type: null,
        status: null,
      },
      form: {
        id: null,
        title: null,
        subTitle: null,
        shopId: null,
        rules: null,
        payValue: 0,
        actualValue: 0,
        type: "0", // 默认普通券
        status: 1, // 默认上架（对应状态值1）
      },
      shopList: [],
      // 类型映射
      typeMap: {
        "0": "普通券",
        "1": "秒杀券",
      },
      typeTagMap: {
        "0": "primary", // 普通券用主色（蓝色）
        "1": "danger", // 秒杀券用危险色（红色）
      },
      // 状态映射
      statusMap: {
        "1": "上架",
        "2": "下架",
        "3": "过期",
      },
      statusTypeMap: {
        "1": "success", // 上架绿色
        "2": "warning", // 下架黄色
        "3": "danger", // 过期红色
      },
      rules: {
        title: [{ required: true, message: "代金券标题不能为空", trigger: "blur" }],
        subTitle: [{ required: true, message: "副标题不能为空", trigger: "blur" }],
        rules: [{ required: true, message: "使用规则不能为空", trigger: "blur" }],
        payValue: [
          { required: true, message: "支付金额(分)不能为空", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (value >= 0 && Number.isInteger(value)) {
                callback();
              } else {
                callback(new Error("请输入有效的非负整数"));
              }
            },
            trigger: "blur",
          },
        ],
        actualValue: [
          { required: true, message: "抵扣金额(分)不能为空", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (value >= 0 && Number.isInteger(value)) {
                callback();
              } else {
                callback(new Error("请输入有效的非负整数"));
              }
            },
            trigger: "blur",
          },
        ],
        type: [{required: true, message: "请选择优惠券类型", trigger: "change"}],
        status: [{required: true, message: "状态不能为空", trigger: "change"}],
      },
    };
  },
  created() {
    getAllShopName()
      .then(res => {
        this.shopList = res.data || [];
      })
      .catch(err => {
        console.error('获取店铺列表失败：', err); // 打印错误，方便排查
      });
    this.getList();
  },
  methods: {
    // 数字输入过滤
    handleNumberInput(field) {
      this.form[field] = parseInt(this.form[field]) || 0;
    },
    // 类型标签方法
    getTypeTag(type) {
      return this.typeTagMap[type] || "info";
    },

    // 状态相关方法
    getStatusType(status) {
      return this.statusTypeMap[status] || "info";
    },
    canToggleStatus(status) {
      return [1, 2].includes(Number(status)); // 允许上架(1)/下架(2)切换，过期(3)不可操作
    },
    getToggleIcon(status) {
      return status === 1 ? "el-icon-close" : "el-icon-check"; // 上架->下架用关闭图标，下架->上架用勾选图标
    },
    getToggleColor(status) {
      return status === 1 ? "#f56c6c" : "#67c23a"; // 上架切换为下架用红色，下架切换为上架用绿色
    },
    getToggleText(status) {
      return status === 1 ? "下架" : "上架";
    },
    toggleStatus(row) {
      const newStatus = row.status === 1 ? 2 : 1; // 1和2互切
      this.$modal
        .confirm(`是否确认将状态切换为【${this.statusMap[newStatus]}】？`)
        .then(() => {
          return changeVoucherStatus(row.id, newStatus);
        })
        .then(() => {
          row.status = newStatus;
          this.$modal.msgSuccess("状态切换成功");
        })
        .catch(() => {
        });
    },

    // 列表查询
    getList() {
      this.loading = true;
      listVoucher(this.queryParams).then((response) => {
        this.voucherList = response.rows.map(item => ({
          ...item,
          // 确保数字字段转换为字符串（与前端存储一致）
          type: item.type.toString(),
          status: item.status.toString()
        }));
        this.total = response.total;
        this.loading = false;
      });
    },

    // 表单重置
    cancel() {
      this.open = false;
      this.reset();
    },
    reset() {
      this.form = {
        id: null,
        title: null,
        subTitle: null,
        rules: null,
        payValue: 0,
        actualValue: 0,
        type: "0", // 重置为普通券
        status: 1, // 重置为上架状态
      };
      this.resetForm("form");
    },

    // 搜索相关
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        title: null,
        type: null,
        status: null,
      };
      this.resetForm("queryForm");
      this.handleQuery();
    },

    // 选中项处理
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },

    // 增删改查操作
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加优惠券";
    },
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getVoucher(id).then((response) => {
        this.form = {
          ...response.data,
          // 强制转换数字字段为整数
          payValue: parseInt(response.data.payValue),
          actualValue: parseInt(response.data.actualValue),
          type: response.data.type.toString(), // 转换为字符串保持一致性
          status: response.data.status.toString(),
        };
        this.open = true;
        this.title = "修改优惠券";
      });
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          // 确保数值字段为非负整数
          this.form.payValue = Math.max(0, parseInt(this.form.payValue));
          this.form.actualValue = Math.max(0, parseInt(this.form.actualValue));
          // 确保类型和状态为字符串（与接口约定一致）
          this.form.type = this.form.type.toString();
          this.form.status = this.form.status.toString();

          if (this.form.id) {
            updateVoucher(this.form).then(() => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addVoucher(this.form).then(() => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm(`是否确认删除优惠券编号为"${ids}"的数据项？`)
        .then(() => {
          delVoucher(ids).then(() => {
            this.getList();
            this.$modal.msgSuccess("删除成功");
          });
        })
        .catch(() => {
        });
    },
    handleExport() {
      this.download("system/voucher/export", {...this.queryParams}, `voucher_${new Date().getTime()}.xlsx`);
    },
  },
};
</script>
